import React, { useState, useEffect } from 'react';
import { Image, List, Empty, Spin, Tag } from 'antd';
import cloudbase from '../../utils/cloudbase';
import styles from './index.module.less';

const ArtworkGallery = ({ category, artist, pageSize = 12 }) => {
  const [loading, setLoading] = useState(false);
  const [artworks, setArtworks] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [imageURLs, setImageURLs] = useState({});

  // 加载作品列表
  const loadArtworks = async (page = 1) => {
    try {
      setLoading(true);
      const result = await cloudbase.getArtworks({
        page,
        pageSize,
        category,
        artist
      });

      if (result.code === 0) {
        setArtworks(result.data.list);
        setTotal(result.data.total);
        // 获取图片URL
        loadImageURLs(result.data.list);
      }
    } catch (error) {
      console.error('加载作品失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取图片临时访问链接
  const loadImageURLs = async (artworkList) => {
    try {
      const urls = {};
      for (const artwork of artworkList) {
        if (artwork.fileID && !imageURLs[artwork.fileID]) {
          const url = await cloudbase.getTempFileURL(artwork.fileID);
          urls[artwork.fileID] = url;
        }
      }
      setImageURLs(prev => ({ ...prev, ...urls }));
    } catch (error) {
      console.error('获取图片链接失败:', error);
    }
  };

  // 页面变化处理
  const handlePageChange = (page) => {
    setCurrentPage(page);
    loadArtworks(page);
  };

  // 初始加载
  useEffect(() => {
    loadArtworks(1);
  }, [category, artist]);

  return (
    <div className={styles.galleryContainer}>
      <Spin spinning={loading}>
        {artworks.length > 0 ? (
          <List
            grid={{
              gutter: 16,
              xs: 1,
              sm: 2,
              md: 3,
              lg: 4,
              xl: 4,
              xxl: 6,
            }}
            dataSource={artworks}
            pagination={{
              current: currentPage,
              pageSize,
              total,
              onChange: handlePageChange
            }}
            renderItem={artwork => (
              <List.Item key={artwork._id} className={styles.artworkItem}>
                <div className={styles.artworkCard}>
                  <div className={styles.imageWrapper}>
                    <Image
                      src={imageURLs[artwork.fileID]}
                      alt={artwork.title}
                      loading="lazy"
                      className={styles.artworkImage}
                      fallback=""
                    />
                  </div>
                  <div className={styles.artworkInfo}>
                    <h3 className={styles.title}>{artwork.title}</h3>
                    <p className={styles.description}>{artwork.description}</p>
                    <div className={styles.tags}>
                      {artwork.tags && artwork.tags.map(tag => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </div>
                  </div>
                </div>
              </List.Item>
            )}
          />
        ) : (
          <Empty description="暂无作品" />
        )}
      </Spin>
    </div>
  );
};

export default ArtworkGallery;